package com.lczyfz.istep.common.utils.domain;

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

/**
 * <p>Created by Charkey on 2017/4/27.</p>
 */
public class DefaultCommandExecutor implements CommandExecutor {

    private Session session;

    private String charset = "UTF-8";

    public DefaultCommandExecutor() {
    }

    public DefaultCommandExecutor(Session session) {
        this.session = session;
    }

    public String exec(String command) {
        ChannelExec channelExec = null;
        BufferedReader reader = null;
        try {
            channelExec = (ChannelExec) session.openChannel("exec");
            channelExec.setCommand(command);
            channelExec.setInputStream(null);
            channelExec.setErrStream(System.err);
            channelExec.connect();
            InputStream in = channelExec.getInputStream();
            reader = new BufferedReader(new InputStreamReader(in, Charset.forName(charset)));
            String buf = null;
            StringBuffer buffer = new StringBuffer();
            while ((buf = reader.readLine()) != null) {
                buffer.append(buf);
            }
            return buffer.toString();
        } catch (JSchException | IOException e) {
            e.printStackTrace();
            return e.getMessage();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (channelExec != null) {
                channelExec.disconnect();
            }
        }
    }
}
